package pers.twf.twfrpc.springboot.starter.bootstrap;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import pers.twf.twfRpc.proxy.ServiceProxyFactory;
import pers.twf.twfrpc.springboot.starter.annotation.RpcReference;

import java.lang.reflect.Field;

/**
 * 消费者启动类
 */
public class RpcConsumerBootstrap implements BeanPostProcessor {
    /**
     * 注入服务
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clazz = bean.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            RpcReference annotation = field.getAnnotation(RpcReference.class);
            if (annotation != null) {
                // 服务注入
                Class<?> interfaceClass = annotation.interfaceClass();
                if (interfaceClass==void.class) {
                    interfaceClass = field.getType();
                }
//                保证私有字段的访问性
                field.setAccessible(true);
                Object proxyObject = ServiceProxyFactory.getProxy(interfaceClass);
                try {
                    field.set(bean,proxyObject);
                    field.setAccessible(false);
                }catch (IllegalAccessException e){
                    throw new RuntimeException("为字段注入代理对象失败",e);
                }
            }
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
